package lujieni.starter.storage;


import lujieni.starter.exception.KeyNotFoundException;
import lujieni.starter.exception.ValueIsNullException;
import lujieni.starter.po.NullObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;
/**
 * @author
 * @Title: RedisCacheStorage
 * @Description:
 * @date 2023/12/7 15:33
 */
public class RedisCacheStorage implements ICacheStorage<String, Object> {

    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Object get(String key) {
        if(StringUtils.isEmpty(key)){
            return null;
        }
        if(Boolean.FALSE.equals(redisTemplate.hasKey(key))){
           throw new KeyNotFoundException();
        }
        Object result = redisTemplate.opsForValue().get(key);
        if(result instanceof NullObject){
            throw new ValueIsNullException();
        }
        return result;
    }

    @Override
    public void set(String k, Object v) {
        redisTemplate.opsForValue().set(k, v);
    }

    @Override
    public void set(String k, Object v, int ttl) {
        redisTemplate.opsForValue().set(k, v, ttl, TimeUnit.MINUTES);
    }

}
